﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace weiqijiance.控制流程
{
    public class socketserverUDP
    {
        ~socketserverUDP()
        {
            //send("关闭软件");
        }
        public mainform m_mainform;
        //Socket sSocket;
        public int port = 7700;
        public string host = "127.0.0.1";

        Socket server;
        EndPoint objendpoint;
        public void connet()
        {
            //objendpoint = new IPEndPoint(IPAddress.Parse(host), port);//绑定端口号和IP 

            objendpoint = new IPEndPoint(IPAddress.Any, port);//绑定端口号和IP 
            server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //server.Bind(new IPEndPoint(IPAddress.Parse(host), port));//绑定端口号和IP
            server.Bind(new IPEndPoint(IPAddress.Any, port));//绑定端口号和IP
            Console.WriteLine("服务端已经开启");
            //Thread t = new Thread(receive);//开启接收消息线程
            //t.Start();
            //Thread t2 = new Thread(sendMsg);//开启发送消息线程
            //t2.Start();

        }
        
        
        /// <summary>
        /// 向特定ip的主机的端口发送数据报
        /// </summary>
        public void send(string sendStr)
        {
            //EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.3.242"), 7100);
            //while (true)
            try
            {
                //string msg = Console.ReadLine();
                //server.SendTo(Encoding.UTF8.GetBytes(sendStr), point);
                byte[] returnData = Encoding.UTF8.GetBytes(sendStr);
                server.SendTo(returnData, returnData.Length, SocketFlags.None, objendpoint);


            }
            catch (Exception )
            { }
 
 
        }
        public string baotou = "";
        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        public string receive()
        {

            try
            {
                baotou = "";
                string recStr = "";
                //byte[] recByte = new byte[4096];
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] recByte = new byte[1024];
                int bytes = server.ReceiveFrom(recByte, ref point);//接收数据报
                string sdata = Encoding.UTF8.GetString(recByte, 0, bytes);
                objendpoint = point;
                //var sdata = System.Text.Encoding.GetEncoding("GB2312").GetString(recByte, 0, bytes);
                if (sdata.Length > 0)
                {
                    if (sdata.Contains("&"))
                    {
                        string[] data = sdata.Split('&');
                        if (data.Length > 1)
                        {
                            baotou = data[0];
                            recStr += data[1];
                        }
                    }
                }


                var Rec_data = string.Format(@"{0}&{1}", baotou, "接收数据成功返回包头");

                send(Rec_data);
                System.Threading.Thread.Sleep(200);
                //recStr += System.Text.Encoding.GetEncoding("GB2312").GetString(recByte, 0, bytes);
                return sdata;
            }
            catch (Exception ex)
            {
                return "断开需要重连" + ex.ToString();
            }

        }

        public void close()
        {
        }
        public void threadopen()
        {
            //控制流程.flowcrtl.m_mainform = this.m_mainform;
            connet();
            string sss = "";
            while (true)
            {
                System.Threading.Thread.Sleep(10);
                //if (bbz)
                {
                    sss = receive();
                    m_mainform.baocunriji("接收到调度发送内容", sss);
                    //if (sss.Contains("断开需要重连"))
                    //{
                    //    sss = "";
                    //    accept();
                    //}
                    //else
                    {
                        dy(sss);

                    }
                    sss = "";
                }
            }
        }

        public void dy(string sml)
        {

            string[] smlsx = sml.Split('&');
            string[] smls = smlsx[1].Split(',');
            if (smls.Length >= 4)
            {
                if (smls[0] == "S")
                {

                    for (int i = 0; i < m_mainform.listflow.Count; i++)
                    {
                        if (smls[2].ToString().Trim() == m_mainform.listflow[i].sshebei.Trim())
                        {
                            //m_mainform.baocunriji("接收333", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                            if (m_mainform.listflow[i].izhuangtai == 1||控制流程.flowcrtl.iquanjuzhuangtai == 1)
                            {
                                send(sml + "," + "工位忙碌中");
                            }
                            else
                            {
                                m_mainform.listflow[i].sDetectID = smls[1];
                                m_mainform.listflow[i].izhuangtai = 2;
                                ////m_mainform.baocunriji("接收到状态", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                                //send(sml + "," + "成功");
                            }
                        }
                    }
                }
                else if (smls[0] == "E")
                {
                    //m_mainform.baocunriji("接收到状态1", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), 333));
                                
                    for (int i = 0; i < m_mainform.listflow.Count; i++)
                    {
                        //m_mainform.baocunriji("接收到状态2", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                                
                        if (smls[2].ToString().Trim() == m_mainform.listflow[i].sshebei.Trim())
                        {
                            //m_mainform.baocunriji("接收到状态3", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                                
                            if (m_mainform.listflow[i].sDetectID == smls[1])
                            {
                                //m_mainform.baocunriji("接收到状态4", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                                
                                if (m_mainform.listflow[i].izhuangtai == 1)
                                {
                                    //m_mainform.baocunriji("接收到状态5", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                                
                                    m_mainform.listflow[i].izhuangtai = 3;
                                    //send(sml + "," + "成功");
                                }
                                else
                                {

                                    //m_mainform.baocunriji("接收到状态6", string.Format("工位名{0}:{1}", smls[2].ToString().Trim(), m_mainform.listflow[i].izhuangtai));
                                
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                send(sml + "," + "成功");

            }

        }
    }
}
